package com.cat.dataStructure;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/split-array-with-minimum-difference/
 * @create 2025/9/28 16:28
 * @since JDK17
 */

public class Solution89 {
    public long splitArray(int[] nums) {
        int n = nums.length;
        boolean[] pre = new boolean[n], suf = new boolean[n];
        long ans = Long.MAX_VALUE, sum = 0, cur = 0;
        pre[0] = suf[n - 1] = true;
        for (int num : nums) {
            sum += num;
        }
        for (int i = 1; i < n && nums[i] > nums[i - 1]; i++) {
            pre[i] = true;
        }
        for (int i = n - 2; i >= 0 && nums[i] > nums[i + 1]; i--) {
            suf[i] = true;
        }
        for (int i = 0; i < n - 1 && pre[i]; i++) {
            cur += nums[i];
            if (pre[i] == true && suf[i + 1] == true) {
                ans = Math.min(ans, Math.abs(sum - cur - cur));
            }
        }

        return ans == Long.MAX_VALUE ? -1 : ans;
    }
}
